package models

import (
	"encoding/json"
	"fmt"
	"ginstudydemo.com/main/dao"
)

// GetMenuRoutes 根据 角色 获取菜单路由列表
func GetMenuRoutes(routes string) (*[]ResRouteInfo, error) {
	var results []ResRouteInfo

	err := dao.Db.Debug().Table("sys_menu t1").
		Select("DISTINCT t1.id, t1.name, t1.parent_id, t1.route_name, t1.route_path, t1.component, t1.icon, t1.sort, t1.visible, t1.redirect, t1.type, t1.always_show, t1.keep_alive, t1.params").
		Joins("INNER JOIN sys_role_menu t2 ON t1.id = t2.menu_id").
		Joins("JOIN sys_role t3 ON t2.role_id = t3.id AND t3.status = 1 AND t3.is_deleted = 0").
		Where("t1.type != '4' AND t3.code IN (?)", routes).
		Order("t1.sort").
		Scan(&results).Error

	if err != nil {
		return nil, err
	}

	//ParamsRaw 字段将用于存储原始 JSON 数据，并解析为 Params，确保在使用过程中不报错。
	for i := range results {
		if results[i].ParamsRaw != "" {

			// 将 JSON 解析为 map
			var data3 map[string]string
			_ = json.Unmarshal([]byte(results[i].ParamsRaw), &data3)

			// 转换为指定格式
			//var result []map[string]string
			for key, value := range data3 {
				results[i].Params = append(results[i].Params, map[string]string{
					"key":   key,
					"value": value,
				})
			}

		}
	}

	return &results, nil
}

// GetMenus 根据 关键词和状态 获取菜单列表
func GetMenus(query GetMenusQuery) (*[]GetMenusRes, error) {
	var results []GetMenusRes

	//Preparing: SELECT id, parent_id, name, type, route_name, route_path, component, perm, visible, sort, icon, redirect, tree_path, keep_alive, always_show, params, create_time, update_time
	//FROM sys_menu WHERE (name LIKE ?) ORDER BY sort ASC

	model := dao.Db.Debug().Table("sys_menu t1").
		Select("id, parent_id, name, type, route_name, route_path, component, perm, visible, sort, icon, redirect, tree_path, keep_alive, always_show, params, create_time, update_time").
		Order("sort ASC")

	// 如果传入了查询条件，则加入模糊查询
	if query.Keywords != "" {
		model = model.Where("name LIKE ? ", "%"+query.Keywords+"%")
	}

	if err := model.Scan(&results).Error; err != nil {
		return nil, err
	}

	return &results, nil

}

// GetMenusOptions 根据 关键词和状态 获取菜单列表
func GetMenusOptions() (*[]GetMenusOptionsRes, error) {
	var results []GetMenusOptionsRes

	//Preparing: SELECT id, parent_id, name, type, route_name, route_path, component, perm, visible, sort, icon, redirect, tree_path, keep_alive, always_show, params, create_time, update_time
	//FROM sys_menu WHERE (name LIKE ?) ORDER BY sort ASC

	model := dao.Db.Debug().Table("sys_menu t1").
		Select("id, parent_id, name, type, route_name, route_path, component, perm, visible, sort, icon, redirect, tree_path, keep_alive, always_show, params, create_time, update_time").
		Order("sort ASC")

	if err := model.Scan(&results).Error; err != nil {
		return nil, err
	}

	return &results, nil

}

// GetMenuInfoById 根据 id 获取菜单
func GetMenuInfoById(id string) (*MenuFormRes, error) {

	//Preparing: SELECT id, parent_id, name, type, route_name, route_path, component, perm, visible, sort, icon, redirect, tree_path, keep_alive, always_show, params, create_time, update_time FROM sys_menu WHERE id = ?

	var result MenuFormRes

	err := dao.Db.Debug().Table("sys_menu").
		Select("id, parent_id, name, type, route_name, route_path, component, perm, visible, sort, icon, redirect, tree_path, keep_alive, always_show, params, create_time, update_time").
		Where("id = ?", id).
		Scan(&result).Error

	if err != nil {
		return nil, err
	}
	return &result, nil

}

// AddMenus 新增菜单
func AddMenus(insertData AddMenusBody) (int64, error) {

	insertData.TypeVal = MapMenuTypeVal(insertData.Type)
	err := dao.Db.Table("sys_menu").Create(&insertData).Error // 通过数据的指针来创建
	return insertData.ID, err
}

// EditMenus 修改菜单
func EditMenus(menus AddMenusBody, menuId string) error {
	fmt.Printf("param: %+v\n", menus)
	menus.TypeVal = MapMenuTypeVal(menus.Type)
	err := dao.Db.Debug().Table("sys_menu").
		//通过 Select 明确指定更新字段。
		Select("always_show", "component", "icon", "keep_alive", "name", "parent_id", "perm", "redirect", "route_name", "route_path", "sort", "type", "visible", "params").
		Where("id = ?", menuId).
		Updates(&menus).Error

	//Create参数需要传入一个指针，所有形参user定义为结构体指针类型
	return err
}

// DelMenus 批量删除菜单（硬删除）
//func DelMenus(ids string) error {
//
//	var idsArr []SysUserId
//	for _, val := range strings.Split(ids, ",") {
//		valNew, _ := strconv.ParseInt(val, 10, 64)
//		idsArr = append(idsArr, SysUserId{
//			ID: valNew,
//		})
//	}
//	err := dao.Db.Debug().Table("sys_menu").Delete(&idsArr).Error
//	return err
//}
